package com.codyy.felix.webconsole.plugins.route.rest;

import com.codyy.felix.webconsole.plugins.route.core.RoutePaths;
import com.codyy.felix.webconsole.plugins.route.utils.TemplateRenderer;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.osgi.framework.BundleContext;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

public abstract class RestServlet extends HttpServlet {


	private static final String RESULT_LIMIT_PARAM = "resultLimit";

	private static final String CACHED_PARAM = "cached";
	private static final String PHRASE_PARAM = "phrase";
	private static final String PROVIDERS_PARAM = "provider";

	protected final BundleContext bundleContext;

	protected final TemplateRenderer templateRenderer;

	public RestServlet(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
		this.templateRenderer = new TemplateRenderer();
	}

	protected abstract String getAliasName();

	public Dictionary<String, Object> createProps() {
		Dictionary<String, Object> props = new Hashtable<>();
		props.put("alias", getAlias());

		return props;
	}

	public String getAlias() {
		return RoutePaths.from(bundleContext).pluginAlias(getAliasName());
	}


	protected Integer getResultLimit(HttpServletRequest request) {
		return Ints.tryParse(StringUtils.trimToEmpty(request.getParameter(RESULT_LIMIT_PARAM)));
	}

	protected Boolean getCached(HttpServletRequest request) {
		return BooleanUtils.toBooleanObject(StringUtils.trimToEmpty(request.getParameter(CACHED_PARAM)));
	}


	protected String getPhrase(HttpServletRequest request) {
		return StringUtils.trimToEmpty(request.getParameter(PHRASE_PARAM));

	}

	protected List<String> getProviders(HttpServletRequest request) {
		final String[] values = request.getParameterValues(PROVIDERS_PARAM);

		return values != null ? Lists.newArrayList(values) : Collections.<String>emptyList();
	}
}
